<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>页面信息管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索与添加 -->
      <el-row class="search">
        <el-col :span="7">
          <el-input
            placeholder="请输入内容"
            v-model="name"
            clearable
            @clear="getInfo"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="search"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" round @click="addProuct"
            >添加商品</el-button
          >
        </el-col>
      </el-row>
      <el-table :data="list" style="width: 100%">
        <el-table-column label="序号" width="90" align="center">
          <template slot-scope="scope">
            {{ scope.$index + 1 }}
          </template>
        </el-table-column>
        <el-table-column
          prop="productId"
          label="产品编号"
          width="40"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="productName"
          label="产品名称"
          width="180"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="cartId"
          label="产品分类"
          width="40"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="productDetail"
          label="产品介绍"
          width="200"
          align="center"
        >
        </el-table-column>
        <el-table-column
          prop="productImage"
          label="产品图片"
          width="200"
          align="center"
        >
          <template slot-scope="scope">
            <!-- 图片显示 -->
            <img
              :src="scope.row.productImage"
              style="width: 100px; height: 100px"
            />
          </template>
        </el-table-column>
        <el-table-column
          prop="price"
          label="产品价格"
          width="120"
          align="center"
        ></el-table-column>
        <el-table-column fixed="right" label="操作" width="120">
          <template slot-scope="scope">
            <el-button @click="handleDelete(scope.row)" type="text" size="small"
              >删除</el-button
            >
            <el-button @click="handleUpdate(scope.row)" type="text" size="small"
              >编辑</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 编辑显示对话框 -->
      <el-dialog title="商品信息" :visible.sync="updateDialogVisible">
        <el-form
          :model="updateForm"
          :rules="editFormRules"
          ref="updateForm"
          label-width="100px"
        >
          <el-form-item label="产品编号" prop="productId">
            <el-input
              v-model="updateForm.productId"
              :disabled="true"
            ></el-input>
          </el-form-item>
          <el-form-item label="产品名称" prop="productName">
            <el-input v-model="updateForm.productName"></el-input>
          </el-form-item>
          <el-form-item label="产品分类" prop="cartId">
            <el-select v-model="updateForm.cartId" @change="handchageup">
              <el-option
                v-for="item in cartListfromBro"
                :key="item.cartId"
                :label="item.cartName"
                :value="item.cartId"
              >{{ item.cartName }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产品价格" prop="price">
            <el-input v-model="updateForm.price"></el-input>
          </el-form-item>
          <el-form-item label="产品介绍" prop="productDetail">
            <el-input v-model="updateForm.productDetail"></el-input>
          </el-form-item>
          <el-form-item label="产品图片" prop="productImage">
            <!-- 图片显示 -->
            <img
              :src="updateForm.productImage"
              style="width: 100px; height: 100px"
            />
            <el-upload
              class="avatar-uploader"
              action="/api/products/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess1"
              :before-upload="beforeAvatarUpload"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <p v-else class="tishi">点击上传新图片</p>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="updateDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="confirmUpdate()">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 添加 -->
      <el-dialog
        title="商品信息"
        :visible.sync="addDialogVisible"
        @close="addformReset"
      >
        <el-form
          :model="addForm"
          :rules="editFormRules"
          label-width="100px"
          ref="addFormRef"
        >
          <el-form-item label="产品名称" prop="productName">
            <el-input v-model="addForm.productName"></el-input>
          </el-form-item>
          <el-form-item label="产品分类" prop="cartId">
            <el-select v-model="addForm.cartId" @change="handchage">
              <el-option
                v-for="item in cartListfromBro"
                :key="item.cartId"
                :label="item.cartName"
                :value="item.cartId"
              >{{ item.cartName }}</el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="产品介绍" prop="productDetail">
            <el-input v-model="addForm.productDetail"></el-input>
          </el-form-item>
          <el-form-item label="产品价格" prop="price">
            <el-input v-model="addForm.price"></el-input>
          </el-form-item>
          <el-form-item label="产品图片" prop="productImage">
            <el-upload
              class="avatar-uploader"
              action="/api/products/upload"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
            >
              <img
                v-if="addForm.productImage"
                :src="addForm.productImage"
                class="avatar"
              />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="add()">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分页查找 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageNum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="pageSize"
        :total="total"
        layout="total,sizes, prev, pager, next, jumper"
      >
      </el-pagination>
    </el-card>
  </div>
</template>

<script>
export default {
  name: "ProductsManage",
  data() {
    return {
      cartListfromBro: [],
      addDialogVisible: false,
      imageUrl: "",
      list: [],
      updateDialogVisible: false,
      updateForm: {
        productId: "",
        productName: "",
        cartId: "",
        productDetail: "",
        productImage: "",
        price:""
      },
      addForm: {
        productName: "",
        cartId: "",
        productDetail: "",
        productImage: "",
        price:""
      },
      pageNum: 1,
      pageSize: 10,
      name: "",
      total: 0,
      editFormRules: {
        productName: [
          { required: true, message: "请输入商品名称", trigger: "blur" },
        ],
        cartId: [
          { required: true, message: "请选择商品分类", trigger: "blur" },
        ],
        productDetail: [
          { required: true, message: "请输入商品介绍", trigger: "blur" },
        ],
        productImage: [
          { required: true, message: "请上传商品图片", trigger: "blur" },
        ],
      },
    };
  },

  created() {
    this.getInfo();
    this.getCart();

    //val接收到从发送方传来的值
  },
  methods: {
    async getCart() {
      const { data: res } = await this.$api.cart.getCart({
        parms: this.queryInfo,
      });

      this.cartListfromBro = res.data;
      console.log(this.cartListfromBro);
    },
    handchage(val) {
      this.addForm.cartId = Number(val);
    },
    handchageup(val) {
      this.updateForm.cartId = val;
    },
    async getInfo() {
      const { data: res } = await this.$api.products.getProducts({
        parms: this.queryInfo,
      });
      this.list = res.data.slice(
        (this.pageNum - 1) * this.pageSize,
        this.pageNum * this.pageSize
      );
      this.total = res.data.length;
    },
    async handleDelete(row) {
      //row为对象
      this.$confirm("此操作将永久删除该数据，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          await this.$api.products.deleteProduct(row.productId);
          this.getInfo();
        })
        .catch(() => {
          // this.dialogVisible = false
        });
    },
    handleUpdate(row) {
      this.updateDialogVisible = true;
      this.updateForm = {
        productId: row.productId,
        productName: row.productName,
        cartId: row.cartId,
        productDetail: row.productDetail,
        productImage: row.productImage,
        price:row.price
      };
    },
    async confirmUpdate() {
      const { data: res } = await this.$api.products.update(this.updateForm);
      if (res.code !== 20031) {
        return this.$message.error("更新用户信息失败！");
      }
      this.updateDialogVisible = false;
      this.getInfo();
      this.$message.success("更新信息成功");
    },
    async search() {
      const { data: res } = await this.$api.products.LikesProduct({
        productName: this.name,
        //将接口中需要的内容写入
      });
      this.list = res.data.slice(
        (this.pageNum - 1) * this.pageSize,
        this.pageNum * this.pageSize
      );
      this.total = res.data.length;
    }, //监听改变事件
    handleSizeChange(val) {
      this.pageSize = val;
      this.getInfo();
    },
    handleCurrentChange(newSize) {
      this.pageNum = newSize;
      this.getInfo();
    },
    addProuct() {
      this.addDialogVisible = true;
    },
    async add() {
      const { data: res } = await this.$api.products.addProduct(this.addForm);
      // 将接口中需要的内容写入
      this.total++;
      if (res.code !== 20011) {
        return this.$message.error("添加商品信息失败！");
      }
      this.addDialogVisible = false;
      this.getInfo();
      this.$message.success("添加商品信息成功");
    },
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === "image/jpeg" ||
        file.type === "image/jpg" ||
        file.type === "image/png";
      // 限制只能3M以内的图片
      const isLt2M = file.size / 1024 / 1024 < 3;

      if (!isJPG) {
        this.$message.error("图片只能是 JPG 或者 PNG 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 3MB!");
      }
      return isJPG && isLt2M;
    },
    handleAvatarSuccess(res) {
      //存入db
      this.addForm.productImage = res.data;
      // this.updateForm.productImage = res.data;
    },
    handleAvatarSuccess1(res) {
      this.updateForm.productImage = res.data;
    },
    addformReset() {
      this.$refs.addFormRef.resetFields();
    },
  },
};
</script>

<style>
.el-breadcrumb {
  margin-top: -15px;
  margin-bottom: 20px;
}
.el-pagination {
  margin-top: 15px;
}
.search {
  margin-left: 40px;
  margin-bottom: 10px;
}
.avatar {
  width: 70px;
  height: 70px;
}
.avatar-uploader {
  display: inline-block;
}
.tishi {
  margin-left: -90px;
}
</style>